package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.EquipmentImage;
import com.guigu.eduservice.entity.EquipmentType;
import com.guigu.eduservice.entity.EquipmentVideo;
import com.guigu.eduservice.mapper.EquipmentMapper;
import com.guigu.eduservice.service.EquipmentImageService;
import com.guigu.eduservice.service.EquipmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.eduservice.service.EquipmentTypeService;
import com.guigu.eduservice.service.EquipmentVideoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.guigu.eduservice.vo.EquipmentVo;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 设备表（存储卖家发布的二手机械信息） 服务实现类
 * </p>
 *
 * @author Xiaosong
 * @since 2025-10-05
 */
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements EquipmentService {
@Autowired
private EquipmentMapper EquipmentMapper;
@Autowired
private EquipmentTypeService equipmentTypeService;
@Autowired
private EquipmentService equipmentService;
@Autowired
private EquipmentImageService equipmentImageService;
@Autowired
private EquipmentVideoService equipmentVideoService;
    @Override
    public List<Equipment> selectFour() {
        return EquipmentMapper.selectNewEquipment();
    }

    @Override
    public Equipment selectById(Long equipmentId) {
        return EquipmentMapper.selectEquipmentImage(equipmentId);
    }
    private List<Long> getAllChildTypeIds(Long parentId) {
        List<Long> typeIds = new ArrayList<>();
        typeIds.add(parentId);
        QueryWrapper<EquipmentType> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<EquipmentType> childTypes = equipmentTypeService.list(wrapper);
        for (EquipmentType child : childTypes) {
            typeIds.addAll(getAllChildTypeIds(child.getTypeId()));
        }
        return typeIds;
    }
    @Override
    public PageInfo<Equipment> queryEquipmentPage(Integer pageNo, Integer pageSize, EquipmentVo vo) {
        System.out.println("开始查询");
        PageHelper.startPage(pageNo, pageSize);
        QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);

        //设备类型筛选
        Long selectedTypeId = vo.getSelectedTypeId();
        if (selectedTypeId != null && selectedTypeId > 0) {
            List<Long> allTypeIds = getAllChildTypeIds(selectedTypeId);
            if (!allTypeIds.isEmpty()) {
                wrapper.in("type_id", allTypeIds);
            }
        }
        //设备型号筛选
        if (vo.getModel() != null && !vo.getModel().isEmpty()){
            wrapper.in("model",vo.getModel());
        }
        //设备品牌筛选
        if (!StringUtils.isEmpty(vo.getBrand())){
            wrapper.eq("brand",vo.getBrand());
        }

        //价格筛选
        if (vo.getMinPrice()!=null) {
            wrapper.ge("price", vo.getMinPrice());
        }
        if (vo.getMaxPrice()!=null) {
            wrapper.le("price", vo.getMaxPrice());
        }
        //省份筛选
        if (!StringUtils.isEmpty(vo.getLocation())){
            wrapper.like("location", vo.getLocation()+"%");
        }

        //时间筛选
        List<String> timeRanges = vo.getTimeRange();
        if (timeRanges != null && !timeRanges.isEmpty()) {
            LocalDateTime endTime = LocalDateTime.now();
            wrapper.and(w -> {
                for (String timeRangeValue : timeRanges) {
                    LocalDateTime startTime = null;
                    boolean isOverThreeMonths = false;
                    switch (timeRangeValue) {
                        case EquipmentVo.TimeRange.ONE_DAY:
                            startTime = endTime.minusDays(1);
                            break;
                        case EquipmentVo.TimeRange.THREE_DAYS:
                            startTime = endTime.minusDays(3);
                            break;
                        case EquipmentVo.TimeRange.ONE_WEEK:
                            startTime = endTime.minusWeeks(1);
                            break;
                        case EquipmentVo.TimeRange.ONE_MONTH:
                            startTime = endTime.minusMonths(1);
                            break;
                        case EquipmentVo.TimeRange.THREE_MONTHS:
                            startTime = endTime.minusMonths(3);
                            break;
                        case EquipmentVo.TimeRange.MORE_THAN_THREE_MONTHS:
                            startTime = endTime.minusMonths(3);
                            isOverThreeMonths = true;
                            break;
                        default:
                            continue;
                    }
                    if (startTime!=null){
                        if (isOverThreeMonths){
                            w.or().le("release_time", startTime);
                        }else {
                            w.or().ge("release_time", startTime);
                        }
                    }

                }
            });
        }

        //排序
        if (!StringUtils.isEmpty(vo.getSortType())){
            switch (vo.getSortType()){
                case EquipmentVo.SortType.PRICE_ASC:
                    wrapper.orderByAsc("price");
                    break;
                case EquipmentVo.SortType.PRICE_DESC:
                    wrapper.orderByDesc("price");
                    break;
                case EquipmentVo.SortType.TIME_DESC:
                    wrapper.orderByDesc("release_time");
                    break;
                case EquipmentVo.SortType.TIME_ASC:
                    wrapper.orderByAsc("release_time");
                    break;
                case EquipmentVo.SortType.HOUR_ASC:
                    wrapper.orderByAsc("hour");
                    break;
                case EquipmentVo.SortType.HOUR_DESC:
                    wrapper.orderByDesc("hour");
                    break;
                case EquipmentVo.SortType.YEAR_ASC:
                    wrapper.orderByAsc("year");
                    break;
                case EquipmentVo.SortType.YEAR_DESC:
                    wrapper.orderByDesc("year");
                    break;
                default:
                    wrapper.orderByDesc("create_time");
                    break;
            }
        }else {
            wrapper.orderByDesc("create_time");

        }
        List<Equipment> equipment = equipmentService.list(wrapper);

        for (int i=0;i<equipment.size();i++){
            Equipment equipments = equipment.get(i);

            // 根据设备typeId查类型名称
            EquipmentType equipmentType = equipmentTypeService.getById(equipments.getTypeId());
            equipments.setTypeName(equipmentType.getTypeName());

            //根据设备id查询设备图片
            QueryWrapper<EquipmentImage> imageQueryWrapper = new QueryWrapper<>();
            imageQueryWrapper.eq("equipment_id",equipments.getEquipmentId());
            List<EquipmentImage> list1 = equipmentImageService.list(imageQueryWrapper);
            if (!list1.isEmpty()) {
                // 获取第一个设备图片
                EquipmentImage firstImage = list1.get(0);
                equipments.setImageUrl(firstImage.getImageUrl());
            }

            //根据设备id查询设备视频
            QueryWrapper<EquipmentVideo> equipmentVideoQueryWrapper = new QueryWrapper<>();
            equipmentVideoQueryWrapper.eq("equipment_id",equipments.getEquipmentId());
            List<EquipmentVideo> equipmentVideoList = equipmentVideoService.list(equipmentVideoQueryWrapper);
            if (!equipmentVideoList.isEmpty()) {
                // 获取第一个设备视频
                EquipmentVideo equipmentVideo = equipmentVideoList.get(0);
                equipments.setVideoUrl(equipmentVideo.getVideoUrl());
            }
        }
        PageInfo<Equipment> equipmentPageInfo = new PageInfo<>(equipment);
        System.out.println("查询到的结果 = " + equipmentPageInfo);
        return equipmentPageInfo;
    }
}
